﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HanGu.Services.Interface;
using HanGu.Entity;
using HanGu.Common;
using System.Net.Mail;

namespace Hangu.WebClient.Controllers.Admin
{
    public class MessageController : AdminBaseController
    {
        private static readonly IMemberInfo serviceMemberInfo = ServiceFactory.GetService<IMemberInfo>();

        //
        // GET: /Message/

        public ActionResult Index()
        {
            SearchParma.IntObj1 = -1;
            return View(viewList, GetMessageList());
        }

        [HttpPost]
        public ActionResult Index(FormCollection collection)
        {

            SearchParma.Pagination.RowCount = null;
            int type_ = -1;
            if (!string.IsNullOrEmpty(Request["IntObj1"]))
            {
                int.TryParse(Request["IntObj1"], out type_);
            }
            SearchParma.IntObj1 = type_;
            int memberid = 0;
            int.TryParse(Request["IntObj2"], out memberid);
            SearchParma.IntObj2 = memberid;
            SearchParma.Suitabler = Request["Suitabler"];
            return View(viewList, GetMessageList());
        }

        List<Message> GetMessageList()
        {
            ViewData["members"] = new SelectList(serviceMemberInfo.GetAll(), "ID", "UserName");
            List<Message> messageList = serviceMessage.GetAll(base.SearchParma);
            ViewData["RowCount"] = SearchParma.Pagination.RowCount;
            return messageList;
        }

        public ActionResult SMS(int id)
        {
            int memberid = 0;
            int.TryParse(Request["memberid"], out memberid);
            Message message = new Message() { GUID = Helper.GetGuid, MemberID = memberid, Type = 0, Title = "发送短信【" + memberid + "】", Receiver = Request["reciever"], CreateTime = DateTime.Now, Creator = CurentUser.UserName };
            if (id > 0)
            {
                message = serviceMessage.GetByID(id);
            }
            else
            {
                message.Receiver = Request["reciever"];
            }
            return View("~/Views/Admin/Message/SMS.cshtml", message);
        }

        //
        // POST: /Message/Create

        [HttpPost]
        [ValidateInput(false)]
        public string SMS(FormCollection collection)
        {
            try
            {
                bool tag = false;
                Message message = new Message();
                string receivers = Request["SMS.Receiver"];
                TryUpdateModel(message, collection);
                if (message.ID > 0)
                {
                    tag = serviceMessage.Update(message);
                }
                else
                {
                    string memberStr = Request["SMS.MemberID"];
                    if (!string.IsNullOrEmpty(memberStr))
                    {
                        //string[] members = memberStr.Split(',');
                        //int memberid = 0;
                        var members = serviceMemberInfo.GetSelectedByGroup(memberStr);

                        if (members != null)
                        {
                            Hangu.WebClient.SMS smsObj = new Hangu.WebClient.SMS();
                            var telList = new List<string>();
                            telList.AddRange(members.Select(c => c.Tel).ToList());
                            smsObj.SMSTo = telList;
                            tag = smsObj.Send();

                        }
                        if (tag)
                        {
                            foreach (var item in members)
                            {
                                //if (int.TryParse(item, out memberid))
                                {
                                    message = new Message();
                                    TryUpdateModel(message, collection);
                                    message.MemberID = item.ID;
                                    message.Receiver = item.Tel;
                                    tag = serviceMessage.Add(message);
                                }
                            }
                        }
                        else
                        {
                            ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", "");
                        }
                    }
                }
                if (tag)
                {
                    ajaxStr = string.Format(ajaxStr, 200, ResourceManager.SaveSuccess, navTabId, "", "closeCurrent");
                }
                else
                {
                    ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", "");
                }
            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", "");
            }
            return "{" + ajaxStr + "}";
        }

        public ActionResult Email(int id)
        {
            int memberid = 0;
            int.TryParse(Request["memberid"], out memberid);
            Message message = new Message() { GUID = Helper.GetGuid, MemberID = memberid, Type = 1, Title = string.Empty, Receiver = Request["reciever"], CreateTime = DateTime.Now, Creator = CurentUser.UserName };
            if (id > 0)
            {
                message = serviceMessage.GetByID(id);
            }
            else
            {
                message.Receiver = Request["reciever"];
            }
            ViewData["Attachments"] = serviceFileManage.GetByGuid(message.GUID);
            return View("~/Views/Admin/Message/Email.cshtml", message);
        }

        [HttpPost]
        [ValidateInput(false)]
        public string Email(FormCollection collection)
        {
            try
            {
                bool tag = false;
                Message message = new Message();
                string receivers = Request["Email.Receiver"];
                TryUpdateModel(message, collection);
                string memberStr = Request["Email.MemberID"];
                var members = serviceMemberInfo.GetSelectedByGroup(memberStr);

                //移动文件
                string newpath = string.Empty;
                MoveToFile(message.GUID, "Email", out  newpath);
                //发EMAIL
                MailMessage mail = new MailMessage();
                var mailList = new List<string>();
                mailList.AddRange(members.Select(c => c.Email).ToList());
                mail.EmailTo = mailList;
                mail.MailSubject = message.Title;
                mail.MailBody = message.Remark;
                //添加附件
                var fileManage = serviceFileManage.GetByGuid(message.GUID);
                List<Attachment> Attachments = new List<Attachment>();
                foreach (var item in fileManage)
                {
                    Attachments.Add(new Attachment(Server.MapPath(item.FilePath)));
                }
                mail.Attachments = Attachments;
                tag = mail.SendMailSMTP();
                if (tag)
                {
                    if (message.ID > 0)
                    {
                        tag = serviceMessage.Update(message);
                    }
                    else
                    {

                        if (!string.IsNullOrEmpty(memberStr))
                        {
                            //string[] members = memberStr.Split(',');
                            //int memberid = 0;
                            foreach (var item in members)
                            {
                                //if (int.TryParse(item, out memberid))
                                {
                                    message = new Message();
                                    TryUpdateModel(message, collection);
                                    message.MemberID = item.ID;
                                    message.Receiver = item.Email;
                                    tag = serviceMessage.Add(message);
                                }
                            }
                        }

                    }
                    if (tag)
                    {
                        ajaxStr = string.Format(ajaxStr, 200, ResourceManager.SaveSuccess, navTabId, "", "closeCurrent");
                    }
                    else
                    {
                        ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", "");

                    }
                }
                else
                {
                    ajaxStr = string.Format(ajaxStr, 300, mail.ErrorMsg, navTabId, "", "");
                }

            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", "");
            }
            return "{" + ajaxStr + "}";
        }


        //
        // GET: /Message/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Message/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Message/Delete/5
        [HttpPost]
        public string Delete(int id, string guid)
        {
            try
            {
                try
                {
                    FileManageController filemanage = new FileManageController();
                    filemanage.DeleteExecute(guid);
                }
                catch { }
                serviceMessage.Delete(id);
                ajaxStr = string.Format(ajaxStr, 200, ResourceManager.DeleteSuccess, navTabId, "", "");
            }
            catch (Exception ex)
            {
                ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.DeleteFail, navTabId, "", "");
            }

            return "{" + ajaxStr + "}";

        }
    }
}
